package com.xiaoshuidi.cloud.module.rooms.controller.admin.rentalspace;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.operatelog.core.annotations.OperateLog;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.rentalspace.vo.*;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomel.vo.RoomelQueryReqVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomequipment.vo.RoomEquipmentExportReq;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomequipment.vo.RoomEquipmentExportRespVo;
import com.xiaoshuidi.cloud.module.rooms.convert.rentalspace.RentalSpaceConvert;
import com.xiaoshuidi.cloud.module.rooms.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.rooms.pojo.roomel.RentalSpaceelEntity;
import com.xiaoshuidi.cloud.module.rooms.service.IRentalSpaceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.zxp.esclientrhl.repository.PageList;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.xiaoshuidi.cloud.framework.common.pojo.CommonResult.success;
import static com.xiaoshuidi.cloud.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Slf4j
@Tag(name = "管理后台 - 空间租赁接口")
@RequestMapping(ApiConstants.NAME +"/rentalspace")
@RestController
@Validated
public class RentalSpaceController {
    @Autowired
    private IRentalSpaceService iRentalSpaceService;

    @PostMapping("/listadd")
    @Operation(summary = "空间租赁推送es接口")
    public CommonResult<Boolean> listadd(@RequestBody List<RentalSpaceCreateReqVO> reqVOS) {
        return CommonResult.success(iRentalSpaceService.listadd(reqVOS));
    }

    @GetMapping("/queryPage")
    @Operation(summary = "空间租赁-分页查询(通过ES)")
    @Parameters({
            @Parameter(name = "pageSize",description = "每页几条数据"),
            @Parameter(name = "pageNum",description = "第几页"),
            @Parameter(name = "searchbox",description = "搜索框"),
            @Parameter(name = "id",description = "编码"),
            @Parameter(name = "name",description = "空间名称"),
            @Parameter(name = "apartmentId",description = "公寓id"),
            @Parameter(name = "type",description = "类型"),
            @Parameter(name = "rentStatus",description = "房态"),
    })
    public CommonResult<PageList<RentalSpaceQueryRespVO>> queryPage(Integer pageSize , Integer pageNum,
           String searchbox,Long id,String name,Long apartmentId,String type,String rentStatus){

        PageList<RentalSpaceelEntity> search = iRentalSpaceService.queryPage(pageNum,pageSize,
                searchbox,id,name,apartmentId,type,rentStatus);

        PageList<RentalSpaceQueryRespVO> rvolist = new PageList<>();

        if(ObjectUtil.isNotEmpty(search)){
            List<RentalSpaceQueryRespVO> list2 = RentalSpaceConvert.INSTANCE.convertList4(search.getList());
            rvolist.setList(list2);
            rvolist.setCurrentPage(search.getCurrentPage());
            rvolist.setPageSize(search.getPageSize());
            rvolist.setTotalPages(search.getTotalPages());
            rvolist.setTotalElements(search.getTotalElements());
            rvolist.setSortValues(search.getSortValues());
        }

        return success(rvolist);
    }

    /**
     * @Description 空间租赁-新增-入数据库和ES库
     * @Param
     * @Return
     * @Date 2023/5/15 10:43
     * @Author Link
     **/
    @PostMapping("/addRentalSpace")
    @Operation(summary = "空间租赁-新增")
    public CommonResult<Boolean> addRentalSpace(@RequestBody RentalSpaceCreateReqVO reqVOS) {

        Long id = iRentalSpaceService.addRentalSpace(reqVOS);

        if(id!=null){
            log.info("空间租赁-新增：入数据库成功");
            reqVOS.setId(id);

            List<RentalSpaceCreateReqVO> reqVOList = new ArrayList<>();
            reqVOList.add(reqVOS);
            Boolean flag2 = iRentalSpaceService.listadd(reqVOList);
            log.info("空间租赁-新增：入ES库成功是否成功："+flag2);
            return CommonResult.success(flag2);
        }
        log.info("空间租赁-新增：失败");
        return CommonResult.success(false);

    }

    @DeleteMapping("/deleteByesid")
    @Operation(summary = "空间租赁-根据id删除")
    @Parameter(name = "id", description = "房间id", required = true)
    public CommonResult<Boolean> deleteByesid(@RequestParam("id") Integer id) {
        log.info("传入的id："+id);
        //入数据库
        Boolean flag1 = iRentalSpaceService.deleteByid(id);
        //入ES库
        if(flag1){
            log.info("空间租赁-删除：入数据库成功");
            Boolean flag2 = iRentalSpaceService.deleteESByid(id);
            if(flag2){
                log.info("空间租赁-删除：入ES库成功");
                return CommonResult.success(flag2);
            }
        }
        log.info("空间租赁-删除：失败");
        return CommonResult.success(false);
    }

    /**
     * @Description 空间租赁-编辑-入数据库和ES库
     * @Param
     * @Return
     * @Date 2023/5/15 11:43
     * @Author Link
     **/
    @PutMapping("/updateRentalSpace")
    @Operation(summary = "空间租赁-编辑")
    public CommonResult<Boolean> updateRentalSpace(@RequestBody RentalSpaceUpdateReqVO reqVOS) {
        //入数据库
        Boolean flag1 = iRentalSpaceService.updateRentalSpace(reqVOS);
        //入ES库
        if(flag1){
            log.info("空间租赁-编辑：入数据库成功");
            Boolean flag2 = iRentalSpaceService.updateEs(reqVOS);
            if(flag2){
                log.info("空间租赁-编辑：入ES库成功");
                return CommonResult.success(flag2);
            }
        }
        log.info("空间租赁-编辑：失败");
        return CommonResult.success(false);
    }

    @Operation(summary = "租赁空间房态计数查询")
    @GetMapping("/queryHouseStateSum")
    @Parameters({
            @Parameter(name = "searchbox",description = "搜索框"),
            @Parameter(name = "id",description = "编码"),
            @Parameter(name = "name",description = "空间名称"),
            @Parameter(name = "apartmentId",description = "公寓id"),
            @Parameter(name = "type",description = "类型"),
    })
    public CommonResult<Map<String,Object>> queryHouseStateSum(String searchbox,Long id,String name,Long apartmentId,String type){

        Map<String,Object> result = iRentalSpaceService.queryHouseStateSum(searchbox,id,name,apartmentId,type);

        return CommonResult.success(result);
    }

    @PutMapping("/updateMonthRental")
    @Operation(summary = "空间租赁定价-更改月租金")
    public CommonResult<Boolean> updateMonthRental(@RequestBody RentalSpaceUpdateReqVO reqVOS) {
        if(ObjectUtil.isEmpty( reqVOS.getMonthRental())){
            throw new IllegalArgumentException("月租金不能为空");
        }

        //入数据库
        Boolean flag1 = iRentalSpaceService.updateRentalSpace(reqVOS);
        //入ES库
        if(flag1){
            log.info("空间租赁定价-更改月租金成功");
            Boolean flag2 = iRentalSpaceService.updateEs(reqVOS);
            if(flag2){
                log.info("空间租赁定价-更改月租金成功");
                return CommonResult.success(flag2);
            }
        }
        log.info("空间租赁定价-更改月租金：失败");
        return CommonResult.success(false);
    }

    @PutMapping("/exportRentalSpace")
    @Operation(summary = "导出空间租赁定价")
    @OperateLog(type = EXPORT)
    public void exportRentalSpace(@RequestBody RentalSpaceExportReqVO exportReqVO){
        // 方法2
        String fileName = "空间租赁定价表" + new SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis()) + ".xlsx";

        List<RentalSpaceExportRespVO> list = iRentalSpaceService.exportRentalSpace(exportReqVO);

        //然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(fileName, RentalSpaceExportRespVO.class).sheet("空间租赁定价").doWrite(list);
    }

    @GetMapping("/queryById")
    @Operation(summary = "查询空间租赁详情")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<RentalSpaceQueryRespVO> queryById(@RequestParam("id") Integer id) {
        log.info("传入的id:"+id);

        RentalSpaceQueryRespVO ret = RentalSpaceConvert.INSTANCE.convert(iRentalSpaceService.queryById(id));

        if( ObjectUtil.isNotEmpty(ret) && StrUtil.isNotBlank( ret.getContractInfo() )){
            Map mapContractInfo = JSONObject.parseObject(ret.getContractInfo(), Map.class);
            ret.setContractInfoMap(mapContractInfo);
        }
        if( ObjectUtil.isNotEmpty(ret) && StrUtil.isNotBlank( ret.getBillInfo() )){
            Map mapBillInfo = JSONObject.parseObject(ret.getBillInfo(), Map.class);
            ret.setBillInfoMap(mapBillInfo);
        }

        return CommonResult.success(ret);
    }

}
